package com.strelitzia.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mysql.cj.util.StringUtils;
import com.strelitzia.admin.Entity.UserEntity;
import com.strelitzia.admin.Entity.UserForm;
import com.strelitzia.admin.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

/**
 * @create 2024/1/23 14:19
 */

@Controller
public class UserController {
    @Autowired
    UserService userService;
    @GetMapping("/account/{page}")
    public String account(@PathVariable("page") int page, Model model) {
        Page<UserEntity> userEntityPage = userService.page(new Page<>(page,10));
        model.addAttribute("users", userEntityPage);
        model.addAttribute("page", page);
        return "account";
    }

    @PostMapping("/account/{page}")
    public String edit(UserForm userForm,@PathVariable("page") int page) {
        if (StringUtils.isNullOrEmpty(userForm.getPassword())) {
            userForm.setPassword(null);
        }else {
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            String password = passwordEncoder.encode(userForm.getPassword());
            userForm.setPassword(password);
        }
        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(userForm,userEntity);
        userService.updateById(userEntity);
        return "redirect:/account/"+page;
    }


    @GetMapping("/account/search")
    public String account(String keyword, Model model) {
        if(StringUtils.isNullOrEmpty(keyword)) {
            return "redirect:/account/1";
        }else {
            Page<UserEntity> userEntityPage = userService.page(new Page<>(1,10),
                    new QueryWrapper<UserEntity>()
                            .eq("username",keyword)
                            .or(w->{w.eq("email",keyword);}));
            model.addAttribute("users", userEntityPage);
            model.addAttribute("page", 1);
            return "account";
        }

    }

    @GetMapping("/account/del/{id}")
    public String del (@PathVariable("id") int id) {
        userService.removeById(id);
        return "redirect:/account/1";
    }
}
